﻿using MediatR;
using S.Authorization.Domain.Model.User;
using S.Authorization.Infrastructure.Interface.User;
using S.Authorization.Read.API.Application.Command.UserCommand;
using S.Authorization.Common.Utilities;
using S.Authorization.Common.Jwt;
using S.Authorization.Read.API.Dto;
using S.Authorization.Infrastructure.Interface.Role;

namespace S.Authorization.Read.API.Application.CommandHandlers.UserCommandHandler
{
    public class UserShowlCommondHandler : IRequestHandler<UserShowlCommond, string>
    {
        private readonly IUserModellRepository userRepository;
        private readonly ICustomJWTService jWTService;
        private readonly IRoleRepository roles;
        private readonly IUserRoleRepository userRole;
        public UserShowlCommondHandler(IUserModellRepository _userRepository, ICustomJWTService _jWTService,IRoleRepository _role,IUserRoleRepository _userRole)
        {
            this.userRepository = _userRepository;
            this.jWTService = _jWTService;
            this.roles = _role;
            this.userRole = _userRole;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> Handle(UserShowlCommond request, CancellationToken cancellationToken)
        {
            
            #region MD5加密
            string hash =Md5Helper.CalculateMd5Hash(request.UserPassWord);
            #endregion
            var user = await userRepository.GetAllAsync();
            var role = await roles.GetAllAsync();
            var userrole = await userRole.GetAllAsync();
            UsersModel userdata = user.FirstOrDefault(x => x.UserName == request.UserName && x.UserPassword == hash);
            if (userdata == null)
            {
                return "false";
            }
            var list = (from a in user
                        join b in userrole
                        on a.UserId equals b.UserId
                        join c in role
                        on b.RoleId equals c.RoleId
                        where a.UserId==userdata.UserId
                        select new UserStrategyDto()
                        {
                            UserId = a.UserId,
                            UserTrueName = a.UserTrueName,
                            RoleId = b.RoleId,
                            RoleName = c.RoleName,
                        }).FirstOrDefault();
            
            string token=jWTService.GetToken(list.UserId,list.RoleName);
            return token;
        }
    }
}
